package com.trivia.fortune.sdk.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;

import com.trivia.fortune.sdk.TrFBusiness;
import com.trivia.fortune.sdk.TrFConstant;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class TrFUtils {

    public static SharedPreferences getSharePrefs() {
        return TrFBusiness.context.getSharedPreferences(TrFConstant.COMMON_SHARE, Context.MODE_PRIVATE);
    }

    public static void putString(String key, String value) {
        getSharePrefs().edit().putString(key, value).commit();
    }

    public static String getString(String key, String defaultValue) {
        return getSharePrefs().getString(key, defaultValue);
    }

    // 固定密钥（长度必须为 16, 24, 或 32 字节）
    private static final String SECRET_KEY = "45dfdfv634dfd634"; // 16 字节（128 位密钥）

    // AES 加密
//    public static String encrypt(String data){
//        try {
//            SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
//            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
//            byte[] encryptedData = cipher.doFinal(data.getBytes());
//            return Base64.encodeToString(encryptedData, Base64.DEFAULT);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return "";
//    }

    // AES 解密
    public static String decrypt(String encryptedData){
        try {
            SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decodedData =  Base64.decode(encryptedData, Base64.DEFAULT);
            return new String(cipher.doFinal(decodedData));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

}
